package util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

public class Util {

	/**
	 * Performs SHA-1 on the target string.
	 * 
	 * @param str
	 *            The target string.
	 * @return the SHA-1 value of <code>str</code>
	 */
	public static String SHA1(String str)
	{
		try
		{
			MessageDigest md = MessageDigest.getInstance("SHA1");
			DigestInputStream dis = new DigestInputStream(new ByteArrayInputStream(str.getBytes("UTF-8")), md);
			while (dis.read() != -1)
				;

			byte[] hash = md.digest();
			Formatter f = new Formatter();
			for (byte b : hash)
			{
				f.format("%02x", b);
			}
			return f.toString();
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static String getSystemPath(String s)
	{
		return s.replaceAll("\\\\", System.getProperty("file.separator"));
	}

	/**
	 * Prints a <code>byte[]</code>, separated by <code>sep</code>
	 * 
	 * @param b
	 * @param sep
	 */
	public static void print(byte[] b, String sep)
	{
		for (byte bb : b)
		{
			System.out.print(bb + sep);
		}
		System.out.println();
	}

	/**
	 * Returns the content of <code>b[]</code> formatted nicely for printing.
	 * 
	 * @param b
	 *            the array to be formated
	 * @param sep
	 *            the separator of each <code>byte[]</code> element.
	 * @return A string with the content of <code>b</code> nicely formatted.
	 */
	public static String printStr(byte[] b, String sep)
	{
		StringBuilder sb = new StringBuilder();
		for (byte bb : b)
		{
			sb.append(bb + sep);
		}
		return sb.toString();
	}

	public static void fill(byte[] toFill, byte[] toRead, int offset)
	{
		for (int i = 0; i < toRead.length; i++)
		{
			toFill[i + offset] = toRead[i];
		}
	}

	/**
	 * Fills an array with the content of another array, starting at position <b>offset[0]</b>
	 * 
	 * @param toFill
	 *            The array which is to be filled by the <b>toRead</b> array.
	 * @param toRead
	 *            The array to be read from
	 * @param offset
	 *            starting position (array because offset[0] should change)
	 */
	public static void fill(byte[] toFill, byte[] toRead, int[] offset)
	{
		for (int i = 0; i < toRead.length; i++)
		{
			toFill[i + offset[0]] = toRead[i];
		}
	}

}
